<script setup>
import { reactive, ref, toRef, onMounted } from 'vue';
import {
  addCandidate,
  uploadImg,
  addPosition,
  checkDuplicate,
  updateResume,
  getPositionList,
} from '../../api/index.js';
import { urlToBase64, dataURLtoFile } from '@/utils/utils';
import {
  handlerWorkList,
  handlerProjectList,
  handlerEducationList,
  getIntention,
  toDataURL,
} from './utils.js';
import DuplicateCheck from './components/DuplicateCheck.vue';
import { ElNotification } from 'element-plus';

const props = defineProps({
  username: String,
});
const emit = defineEmits(['changeType']);

// 退出登录
const logout = () => {
  emit('changeType', 'login');
  // 重置采集数据
  Object.assign(resume, getInitialResume());
  // 清空storage
  chrome.storage.local.clear();
};

const getInitialResume = () => ({
  base: {},
  desired: {},
  emailImage: null,
  phoneImage: null,
  evaluation: null,
  htmlFile: null,
  other: {},
  projectList: [],
  workList: [],
  educationList: [],
  schoolName: '',
  majorName: '',
  companyName: '',
  jobName: '',
});
// 候选人简历信息
let resume = reactive(getInitialResume());

// 获取当前tab标签
const getCurrentTab = async () => {
  let queryOptions = { active: true, currentWindow: true };
  let [tab] = await chrome.tabs.query(queryOptions);
  return tab;
};
//  sendMessage
const sendMessageToContentScript = async (message) => {
  const tab = await getCurrentTab();
  return await chrome.tabs.sendMessage(tab.id, message);
};

// 点击采集按钮
const handleCollection = async () => {
  // console.info("点击’采集按钮‘");
  duplicateCheckDisabled.value = false;
  joinDisabled.value = true;
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '采集信息中...',
    // text: '采集信息中: 若是无忧精英网站，需要对手机邮箱图片进行识别，可能稍慢',
    spinner: 'el-icon-loading',
  });

  console.info('点击’采集按钮‘');

  // 发送采集消息通知到content-script
  const res = await sendMessageToContentScript({ action: 'collection' });
  loadingInstance.close();

  if (res.status === 0) {
    console.log(res.data);
    // console.log(res);
    resume.schoolName = res.data.educationList[0].school;
    resume.majorName = res.data.educationList[0].majorName;
    resume.companyName = res.data.workList[0].company;
    resume.jobName = res.data.workList[0].jobName;
    Object.assign(resume, res.data);
    chrome.storage.local.set({ candidateInfo: JSON.stringify(resume) });
  } else {
    ElMessage.error(res.message || 'error!');
  }
};

// 点击简历查重
let duplicateCheckShow = ref(false);
let accurate = ref();
let vague = ref();
let duplicateCheckDisabled = ref(false);

const handleDuplicateCheck = async () => {
  let workList = resume.workList;
  const data = {
    mobile: resume.base.phone,
    name: resume.base.name,
    birthday: resume.base.birth,
    position: resume.jobName,
    companyName: resume.companyName,
    employmentStartYear: workList[workList.length - 1].startTime.split('-')[0],
    employmentEndYear: workList[0].endTime.split('-')[0],
  };
  const res = await checkDuplicate(data);
  if (res.success) {
    if (res.accurate.total || res.vague.total) {
      accurate.value = res.accurate;
      vague.value = res.vague;
      duplicateCheckShow.value = true;
    } else {
      ElNotification({
        title: 'Success',
        message: '未找到相似简历，请放心导入',
        type: 'success',
      });
      duplicateCheckDisabled.value = true;
      joinDisabled.value = false;
    }
  }
};

const duplicateCheckBack = (value) => {
  duplicateCheckShow.value = value;
  console.log(accurate);
  if (!accurate.value.total && !vague.value.total) {
    duplicateCheckDisabled.value = true;
    joinDisabled.value = false;
  }
};

const updateResumeBtn = async (uid) => {
  const data = await handlerForm();
  if (!data) return;
  data.uid = uid;
  const res = await updateResume(data);
  if (res.success) {
    ElMessage.success(`${data.name}更新简历成功！`);
    handleDuplicateCheck();
  }
};

const duplicateCheckAddPosition = (uid) => {
  duplicateCheckUid.value = uid;
  addPositionShow.value = true;
  handleAddPosition();
};

let joinDisabled = ref(true);
// 加入简历库
const handleAddResume = async () => {
  const data = await handlerForm();
  if (!data) return;
  const res = await addCandidate(data);
  if (res.success) {
    ElMessage.success(`${data.name}加入简历库成功！`);
    // 重置采集数据
    Object.assign(resume, getInitialResume());
    duplicateCheckDisabled.value = false;
    joinDisabled.value = true;
  }
};

const handlerForm = async () => {
  const {
    base, // 基本信息
    desired, // 期望工作信息
    educationList, // 教育经历
    evaluation, // 个人评价
    other, // 其他- 证书
    projectList, // 项目经历
    workList, // 工作经历
  } = resume;

  // 处理图片上传
  let imgUrl = '';
  if (base.photoUrl) {
    const imgBase64 = await toDataURL(resume.base.photoUrl);
    const imgBlob = dataURLtoFile(imgBase64, 'img');
    let form = new FormData();
    form.append('file', imgBlob);
    const res = await uploadImg(form);
    imgUrl = res.url;
    if (!res.success) return;
  }

  return {
    isPlug: true,
    photoUrl: imgUrl, // 头像

    name: base.name, // 中文名
    sex: base.sex === '男' ? '1' : base.sex === '女' ? '2' : '3', // 性别
    mobile: base?.phone, // 手机号
    email: base?.email, // 邮箱
    birthday: base?.birth, // 生日
    age: +base?.age, // 年龄
    currentCity: base.nowCity, // 当前城市
    // salary: base.nowCity, // 当前年薪
    currentIntention: getIntention(base.status), // 当前意向

    skill: base.skill, // 个人技能
    maritalStatus: base.maritalStatus, // 婚姻状态
    //、专业
    // nativePlace: base.nativePlace, // 籍贯
    currentCity: base.nowCity, // 当前城市
    cityName: desired?.desiredCitys, // 意向城市
    desireSalary: desired.desiredSalary, // 期望薪资
    desireLocation: desired.desiredCitys, // 期望地点
    positionName: desired.desiredJobName, // 意向职位名称

    source: 6, // 录入来源
    workList: handlerWorkList(workList), // 工作经历
    educationList: handlerEducationList(educationList), // 教育经历
    projectList: handlerProjectList(projectList), // 项目经历
  };
};

// 加入职位
let addPositionShow = ref(false);

let selectPosition = reactive({
  tableData: [],
  page: 1,
  pageSize: 5,
  total: 0,
  companyName: '',
  positionName: '',
});

const handleAddPosition = async () => {
  const res = await getPositionList(selectPosition);
  if (res.success) {
    selectPosition.tableData = res.data;
    selectPosition.total = res.total;
    addPositionShow.value = true;
  }
};

const search = () => {
  selectPosition.page = 1;
  handleAddPosition();
};

const changePage = (page) => {
  selectPosition.page = page;
  handleAddPosition();
};

let duplicateCheckUid = ref(null);
const addPositionBtn = async (row) => {
  if (!duplicateCheckShow.value) {
    const data = await handlerForm();
    if (!data) return;
    data.companyId = row.companyLikeId;
    data.positionId = row.id;
    const res = await addPosition(data);
    if (res.success) {
      ElMessage.success(
        `${data.name}加入${row.companyLike}的${row.nameLike}职位成功！`,
      );
      // 重置采集数据
      Object.assign(resume, getInitialResume());
      duplicateCheckDisabled.value = false;
      joinDisabled.value = true;
    }
  } else {
    let data = {
      companyId: row.companyLikeId,
      positionId: row.id,
      uid: duplicateCheckUid.value,
    };
    const res = await addPosition(data);
    if (res.success) {
      ElMessage.success(
        `候选人加入${row.companyLike}的${row.nameLike}职位成功！`,
      );
    }
  }
  addPositionShow.value = false;
};

// 生命周期钩子函数
onMounted(() => {
  chrome.storage.local.get(['candidateInfo'], function (res) {
    if (res['candidateInfo']) {
      Object.assign(resume, JSON.parse(res['candidateInfo']));
    }
  });
});
</script>

<template>
  <!--   登录用户信息   -->
  <el-row :gutter="20" align="middle">
    <el-col :span="18">
      <div class="username">当前登录账户: {{ props.username }}</div>
    </el-col>
    <el-col :span="6">
      <el-button type="primary" size="small" @click="logout">退出</el-button>
    </el-col>
  </el-row>

  <template v-if="!duplicateCheckShow">
    <!--    候选人详细信息    -->
    <el-row>
      <el-card class="box-card">
        <el-form
          :model="resume"
          size="small"
          label-width="60px"
          label-position="left"
        >
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="resume.base.name"
              placeholder="姓名"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="desiredCitys">
            <el-input v-model="resume.base.phone" placeholder="手机"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-input
              v-model="resume.base.sex"
              placeholder="性别"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input
              v-model="resume.base.age"
              placeholder="姓名"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="学历" prop="qualifications">
            <el-input
              v-model="resume.base.qualifications"
              placeholder="学历"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="毕业院校" prop="schoolName">
            <el-input
              v-model="resume.schoolName"
              placeholder="毕业院校"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="专业" prop="majorName">
            <el-input
              v-model="resume.majorName"
              placeholder="毕业院校"
              size="small"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="所属行业" prop="industry">
            <el-input
              v-model="resume.base.currentIndustry"
              placeholder="所属行业"
              size="small"
            ></el-input>
          </el-form-item> -->
          <el-form-item label="当前状态" prop="status">
            <el-input
              v-model="resume.base.status"
              placeholder="当前状态"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="所在城市" prop="nowCity">
            <el-input
              v-model="resume.base.nowCity"
              placeholder="所在城市"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="意向城市" prop="desiredCitys">
            <el-input
              v-model="resume.desired.desiredCitys"
              placeholder="意向城市"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="意向岗位" prop="desiredJobName">
            <el-input
              v-model="resume.desired.desiredJobName"
              placeholder="意向岗位"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="期望薪资" prop="desiredSalary">
            <el-input
              v-model="resume.desired.desiredSalary"
              placeholder="期望薪资"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="最近公司" prop="companyName">
            <el-input
              v-model="resume.companyName"
              placeholder="最近公司"
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item label="最近职位" prop="jobName">
            <el-input
              v-model="resume.jobName"
              placeholder="最近职位"
              size="small"
            ></el-input>
          </el-form-item>
        </el-form>
      </el-card>
    </el-row>

    <!--   候选人操作     -->
    <el-row>
      <!--          <el-button type="primary" @click="handleGetSource">测试请求</el-button>-->
      <el-button type="primary" size="small" @click="handleCollection"
        >抓取简历</el-button
      >
      <el-button
        type="success"
        :disabled="duplicateCheckDisabled"
        size="small"
        @click="handleDuplicateCheck"
        >简历查重</el-button
      >
      <el-button
        type="info"
        size="small"
        @click="handleAddResume"
        :disabled="joinDisabled"
        >加入简历库</el-button
      >
      <el-button
        type="warning"
        size="small"
        @click="handleAddPosition"
        :disabled="joinDisabled"
        >加入职位</el-button
      >
    </el-row>
  </template>
  <template v-if="duplicateCheckShow">
    <DuplicateCheck
      v-model:accurate="accurate"
      v-model:vague="vague"
      @back="duplicateCheckBack"
      @addPositionBtn="duplicateCheckAddPosition"
      @updateResume="updateResumeBtn"
    />
  </template>

  <el-dialog v-model="addPositionShow" title="选择加入职位" width="80%">
    <div class="search">
      <el-input v-model="input" placeholder="职位名称" />
      <el-input v-model="input" placeholder="客户公司" style="margin: 0 15px" />
      <el-button type="primary" @click="search">搜索</el-button>
    </div>

    <el-table :data="selectPosition.tableData" style="width: 100%">
      <el-table-column prop="nameLike" label="职位名称" width="100" />
      <el-table-column prop="companyLike" label="客户公司" width="100" />
      <el-table-column fixed="right" label="操作" width="70">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="addPositionBtn(scope.row)"
            >加入职位</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination" v-if="selectPosition.total">
      <el-pagination
        layout="prev, pager, next"
        :page="selectPosition.page"
        :page-size="5"
        @current-change="changePage"
        :total="selectPosition.total"
      />
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
.el-card__body {
  padding: 20px 20px 10px 20px;
}

.username {
  font-size: 16px;
  color: #666;
}

.el-row + .el-row {
  margin-top: 12px;
}

.box-card {
  height: 390px;
  width: 300px;
  overflow-y: auto;
}

.resume-left-container {
  li {
    padding: 10px 0;

    img {
      width: 100%;
    }
  }
}

.search {
  display: flex;
  margin-bottom: 10px;
}
.pagination {
  width: 100%;
  display: flex;
  justify-content: center;
}
</style>
